<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="">
        <span style="color: rgba(0, 145, 255, 1)">共计（个）：{{ total }}</span>
      </el-form-item>
      <el-form-item label="" prop="querysele">
        <el-input placeholder="请输入" v-model="querysele" class="input-with-select" style="width: 400px">
          <el-select v-model="house" slot="prepend" placeholder="请选择" style="width: 130px">
            <!-- <el-option label="服务类型" value="serveTypeName"></el-option> -->
            <el-option label="工作年限" value="yearNum"></el-option>
            <el-option label="人员姓名" value="name"></el-option>
          </el-select>
          <!-- <el-button slot="append" icon="el-icon-search"></el-button> -->
        </el-input>
      </el-form-item>
      <el-form-item label="" prop="name">
        <el-select v-model="queryParams.serveType" placeholder="请选择服务类型">
          <el-option v-for="item in fuwutypes" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="time">
        <el-date-picker v-model="time" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" @change="changetime" value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:laborer:add']">发布</el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:laborer:remove']">删除</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:laborer:export']">导出</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="laborerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="服务类型" align="center" prop="serveTypeName" label-class-name="table-th-active" />
      <el-table-column label="服务内容" align="center" prop="contents" label-class-name="table-th-active"
        show-overflow-tooltip />
      <el-table-column label="价位" align="center" label-class-name="table-th-active">
        <template slot-scope="scope">
          <span>{{ scope.row.serveMoney }}{{ scope.row.serveMoneyStr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人员姓名" align="center" prop="name" show-overflow-tooltip
        label-class-name="table-th-active" />
      <el-table-column label="电话" align="center" prop="phone" label-class-name="table-th-active" />
      <el-table-column label="年龄" align="center" prop="age" label-class-name="table-th-active" />
      <el-table-column label="工作年限" align="center" prop="yearNum" label-class-name="table-th-active" />
      <el-table-column label="地区" align="center" prop="addressThreeStr" label-class-name="table-th-active"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.addressOneStr }}{{ scope.row.addressTwoStr }}{{ scope.row.addressThreeStr }}{{ scope.row.addressFourStr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handledet(scope.row)" v-hasPermi="['system:laborer:remove']">详情
          </el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['system:laborer:edit']">修改
          </el-button>
          <el-button size="mini" type="text" @click="handleyuyue(scope.row)" v-hasPermi="['system:laborer:edit']">预约
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改家政人员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="">
          <img style="width: 100px" :src="form.iconUrl" alt="">
        </el-form-item>
        <el-form-item label="">
          {{ form.name }}
          {{ form.addressOneStr }}-{{ form.addressTwoStr }}-{{ form.addressThreeStr }}-{{ form.addressForeStr }}
        </el-form-item>
        <el-form-item label="" prop="age">
          {{ form.age }} |
          {{ form.yearNum }} |
          <span>{{ zuo }},{{ jia }},{{ zhao }},{{ lao }}</span>
        </el-form-item>
        <el-form-item label="" prop="serveMoney">
          <span>{{ zuo }},{{ jia }},{{ zhao }},{{ lao }}</span>
          <span style="margin-left: 20px" v-if="form.serveMoney">{{ form.serveMoney }} 元</span>
        </el-form-item>
        <el-divider content-position="center">账号信息</el-divider>
        <el-form-item label="手机号">
          <el-input v-model="phone" placeholder="请输入预约账号" @blur="getphone" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="namesss" placeholder="请输入预约人姓名" disabled />
        </el-form-item>
        <el-divider content-position="center">预约人信息</el-divider>
        <el-form-item label="预约人姓名">
          <el-input v-model="subUserName" placeholder="请输入预约人姓名" />
        </el-form-item>
        <el-form-item label="预约人电话">
          <el-input v-model="subPhone" placeholder="请输入预约人电话" />
        </el-form-item>
        <el-form-item label="预约人地区">
          <el-cascader v-model="addressList" style="width: 100%" :props="props"></el-cascader>
          <el-input style="margin-top: 20px" v-model="addressDetail" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="预约时段">
          <el-date-picker v-model="subDate" @change="DateChange" type="date" placeholder="选择日期"
            value-format="yyyy-MM-dd" :picker-options="picheroption">
          </el-date-picker>
          <el-select v-model="subTime" multiple placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">预 约</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listLaborer,
    getLaborer,
    delLaborer,
    addLaborer,
    updateLaborer,
    getregion,
    getphone,
    getorder
  } from "@/api/system/laborer";
  import {
    getOneOrder
  } from "@/api/system/order";
  var addressStrList = []
  export default {
    name: "Laborer",
    data() {
      return {
        options: [],
        hasYyOrder: [], // 某个家政人员已经预约的订单
        picheroption: {
          disabledDate(time) {
            let now = new Date()
            let h = now.getHours()
            let nowDate = new Date(
              now.getFullYear(),
              now.getMonth(),
              now.getDate() + 1
            );
            let monthago = new Date(
              now.getFullYear(),
              now.getMonth() + 1,
              now.getDate()
            );
            return (
              time.getTime() < nowDate.getTime() - 1000 ||
              time.getTime() > monthago.getTime()
            );
          }
        },
        userId: '',
        namesss: '',
        subUserName: '',
        subPhone: '',
        addressList: [],
        addressDetail: '',
        subDate: '',
        subTime: [],
        phone: '',
        imgyrl: 'http://192.168.31.230:8080',
        props: {
          lazy: true,
          lazyLoad(node, resolve) {
            if (node.data) {
              if (node.data.parentId === '0') {
                addressStrList = []
              }
              addressStrList.push(node.data)
            }
            const {
              level
            } = node;
            let data = []
            let id = 0
            console.log(level)
            if (level != 0) {
              id = node.value
            }
            getregion(id).then(res => {
              res.rows.map(item => {
                let obj = {
                  value: item.id,
                  label: item.name,
                  parentId: item.parentId
                }
                data.push(obj)
              })
              resolve(data);
            });
          }
        },
        fuwutypes: [{
          value: '1',
          label: '住家'
        }, {
          value: '2',
          label: '白班'
        }, {
          value: '3',
          label: '钟点工'
        }],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedJzLaborerHistory: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 家政人员表格数据
        laborerList: [],
        // 家政人员工作经历表格数据
        jzLaborerHistoryList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          createTimeSta: '',
          createTimeEnd: '',
          serveType: ''
        },
        time: [],
        querysele: '',
        house: '',
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "姓名不能为空",
            trigger: "blur"
          }],
          phone: [{
            required: true,
            message: "手机号不能为空",
            trigger: "blur"
          }],
        },
        zuo: '',
        jia: '',
        zhao: '',
        lao: ''
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询家政人员列表 */
      getList() {
        this.loading = true;
        const housename = this.house
        let parse = {
          ...this.queryParams,
        }
        parse[housename] = this.querysele
        listLaborer(parse).then(response => {
          this.laborerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.phone = ''
        this.userId = ''
        this.subUserName = ''
        this.subPhone = ''
        this.addressList = ''
        this.addressDetail = ''
        this.subDate = ''
        this.subTime = ''
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          phone: null,
          addressOneId: null,
          addressOneStr: null,
          addressTwoId: null,
          addressTwoStr: null,
          addressThreeId: null,
          addressThreeStr: null,
          addressDetail: null,
          birthData: null,
          age: null,
          sex: null,
          yearNum: null,
          sort: null,
          iconUrl: null,
          serveType: null,
          serveTypeName: null,
          serveMoney: null,
          serveMoneyStr: null,
          tel: null,
          status: 0,
          createId: null,
          createTime: null,
          updateId: null,
          updateTime: null,
          delFlag: null
        };
        this.jzLaborerHistoryList = [];
        this.resetForm("form");
        this.phone = '';
        this.userId = '';
        this.subUserName = '';
        this.subPhone = '';
        this.addressList = '';
        this.addressDetail = '';
        this.subDate = '';
        this.subTime = [];
      },
      changetime(val) {
        // console.log(val)
        this.time = val
        this.queryParams.createTimeSta = this.time[0]
        this.queryParams.createTimeEnd = this.time[1]
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams = {
            pageNum: 1,
            pageSize: 10,
            createTimeSta: '',
            createTimeEnd: '',
            serveType: '',
          },
          this.house = ''
        this.querysele = ''
        this.time = []
        this.queryParams.createTimeSta = ''
        this.queryParams.createTimeEnd = ''
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        // console.log(selection)
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$router.push({
          path: '/houseadd'
        })
        // this.reset();
        // this.open = true;
        // this.title = "添加家政人员";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.$router.push({
          path: '/houseadd',
          query: {
            id: row.id
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        console.log(row)
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除家政人员的数据？').then(function() {
          return delLaborer(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      // 详情
      handledet(row) {
        this.$router.push({
          path: '/housedet',
          query: {
            id: row.id
          }
        })
      },
      /** 家政人员工作经历序号 */
      rowJzLaborerHistoryIndex({
        row,
        rowIndex
      }) {
        row.index = rowIndex + 1;
      },
      /** 家政人员工作经历添加按钮操作 */
      handleAddJzLaborerHistory() {
        let obj = {};
        obj.laborerTypeStr = "";
        obj.timeStart = "";
        obj.timeEnd = "";
        obj.historyDetail = "";
        obj.createId = "";
        obj.updateId = "";
        this.jzLaborerHistoryList.push(obj);
      },
      /** 家政人员工作经历删除按钮操作 */
      handleDeleteJzLaborerHistory() {
        if (this.checkedJzLaborerHistory.length == 0) {
          this.$modal.msgError("请先选择要删除的家政人员工作经历数据");
        } else {
          const jzLaborerHistoryList = this.jzLaborerHistoryList;
          const checkedJzLaborerHistory = this.checkedJzLaborerHistory;
          this.jzLaborerHistoryList = jzLaborerHistoryList.filter(function(item) {
            return checkedJzLaborerHistory.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleJzLaborerHistorySelectionChange(selection) {
        this.checkedJzLaborerHistory = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/laborer/export', {
          ...this.queryParams
        }, `laborer_${new Date().getTime()}.xlsx`)
      },
      // 预约
      handleyuyue(row) {
        const id = row.id
        getLaborer(id).then(response => {
          response.data.contentsList.forEach(item => {
            if (item == 1) {
              this.zuo = '做饭'
            } else if (item == 2) {
              this.jia = '做家务'
            } else if (item == 3) {
              this.zhao = '照顾小孩'
            } else if (item == 4) {
              this.lao = '照顾老人'
            }
          });
          response.data.timesList.sort();
          this.form = response.data;
        });
        getOneOrder(id).then(res => {
          let Time = []
          res.data.forEach((item) => {
            item.month = item.subDate
            let times = item.subTime.split(',')
            let timesArr = times.map((itemtime) => {
              return item.month + ' ' + itemtime
            })
            Time = Time.concat(timesArr)
          });
          this.hasYyOrder = Time;
        });
        this.open = true
      },
      DateChange(e) {
        this.subTime = []
        this.options = []
        console.log(e)
        let timeList = this.form.timesList
        for (let i = 0; i < timeList.length; i++) {
          if (this.hasYyOrder.includes(e + ' ' + timeList[i])) {

          } else {
            this.options.push({
              value: timeList[i],
              label: timeList[i]
            })
          }
        }
      },
      getphone() {
        if (this.phone == '') {
          this.$message.error('基本信息手机号不能为空！');
          return false
        }
        getphone(this.phone).then(res => {
          // console.log(res)
          if (res.code == 200) {
            this.namesss = res.data.uname
            this.userId = res.data.id
          }
        }).catch(err => {
          this.namesss = ''
          this.userId = ''
          this.phone = ''
        })
      },
      /** 预约按钮 */
      submitForm() {
        if (this.phone == '') {
          this.$message.error('账号信息：手机号不能为空！');
          return false
        }
        if (this.subUserName == '') {
          this.$message.error('请输入预约人姓名');
          return false
        }
        if (this.subPhone == '') {
          this.$message.error('请输入预约人电话');
          return false
        }
        if (this.addressList == '') {
          this.$message.error('请选择预约人地区');
          return false
        }
        if (this.addressDetail == '') {
          this.$message.error('请输入详细地址');
          return false
        }
        let sss = []
        addressStrList.forEach(item => {
          sss.push(item.label)
        })
        if (this.subTime.length == 0) {
          this.$message.error('请选择预约时间');
          return false
        }
        let parse = {
          jzLaborer: this.form,
          userMobile: this.phone,
          userId: this.userId,
          subUserName: this.subUserName,
          subPhone: this.subPhone,
          addressList: this.addressList,
          addressDetail: this.addressDetail,
          subDate: this.subDate,
          subTime: this.subTime.join(','),
          addressStrList: sss
        }

        getorder(parse).then(res => {
          // console.log(res)
          this.$modal.msgSuccess("预约成功");
          this.open = false
          this.getList();
          this.reset();
        });
      },
    }
  };
</script>
